package com.pro_one.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pro_one.constant.MessageConstant;

import com.pro_one.entity.PageResult;
import com.pro_one.entity.QueryPageBeanQueryString;
import com.pro_one.dao.*;
import com.pro_one.entity.Result;
import com.pro_one.pojo.*;
import com.pro_one.service.OrderService;
import com.pro_one.util.DateUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
   @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private MealsDao mealsDao;
    @Autowired
    private ExerciseDao exerciseDao;
    /**
     * 新增预约
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Result order(Map map, Integer orderaddressId) throws Exception {
         /*验证这一天可不可以预约
            如果可以预约，看还有没有剩余预约人数
            验证之前有没有预约过，是否重复预约
            验证是否是会员，如果是就添加预约信息
            不是会员创建新会员。
            更新当天的预约人数
         * */
        String date = (String) map.get("orderDate");
        Date orderDate = DateUtils.parseString2Date(date);
        String name = (String) map.get("name");
        String setmealId = (String) map.get("setmealId");
        OrderSetting orderSetting = orderSettingDao.findByOrderdate(orderDate);
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (number <= reservations) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            Order order = new Order(null, member.getId(), orderDate, null, null, Integer.parseInt(setmealId));
            List<Order> orderList = orderDao.findByOrder(order);
            if (orderList != null && orderList.size() > 0) {
                return new Result(false, "会员当日不可以重复预约");
            }
        } else {
            member = new Member();
            member.setName(name);
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }
        Order order = new Order(null, member.getId(), orderDate, Order.ORDERTYPE_WEIXIN, Order.ORDERSTATUS_NO, Integer.parseInt(setmealId));
        orderDao.add(order);
        Integer id = order.getId();
        orderDao.addOrderIdAndAddressId(id, orderaddressId);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS, id);
    }

    /**
     * 查询后展示页面预约成功信息
     *
     * @param id
     * @return
     */
    @Override
    public Map findById(Integer id) {
        return orderDao.findById(id);
    }

    @Override
    public PageResult PageQuery(QueryPageBeanQueryString queryPageBean) {
        Map<String, Object> queryString = queryPageBean.getQueryString();
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        PageHelper.startPage(currentPage, pageSize);
        Page<Order> page = orderDao.pageQuery(queryString);
        long total = page.getTotal();
        List<Order> result = page.getResult();
        return new PageResult(total, result);
    }

    @Override
    public Result add(Map<String, Object> map, List<Integer> lsetmealIds) throws Exception {
        String telephone = (String) map.get("phoneNumber");
        String orderDate = (String) map.get("orderDate");
        Date oDate = DateUtils.parseString2Date(orderDate);
        String name = (String) map.get("name");
        OrderSetting orderSetting = orderSettingDao.findByOrderdate(oDate);
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        int reservations = orderSetting.getReservations();
        int number = orderSetting.getNumber();
        if (reservations >= number) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            for (Integer setmealId : lsetmealIds) {
                Order order = new Order(null, member.getId(), DateUtils.parseString2Date(orderDate), Order.ORDERTYPE_TELEPHONE, Order.ORDERSTATUS_NO, setmealId);
                List<Order> orderList = orderDao.findByOrder(order);
                if (orderList != null && orderList.size() > 0) {
                    return new Result(false, "会员当日不可以重复预约");
                }
            }

        } else {
            member = new Member();
            member.setName(name);
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberDao.add(member);
        }
        for (Integer setmealId : lsetmealIds) {
            Order order = new Order(null, member.getId(), DateUtils.parseString2Date(orderDate), Order.ORDERTYPE_TELEPHONE, Order.ORDERSTATUS_NO, setmealId);
            orderDao.add(order);
        }
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS);
    }

    @Override
    public Map findByOrderId(Integer id) {
        return orderDao.findByOrderId(id);
    }

    @Override
    public List<Integer> findSetmealIdsByOrderId(Integer id) {
        return orderDao.findSetmealIdsByOrderId(id);
    }
//编辑
    @Override
    public void edit(Map map, List<Integer> setmealIds) {
        Integer id = (Integer) map.get("id");
        String name = (String) map.get("memberName");
        String datestr = (String) map.get("orderDate");
        Date date = null;
        try {
            date = DateUtils.parseString2Date(datestr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String orderType = (String) map.get("orderType");
        String orderStatus = (String) map.get("orderStatus");
        Integer memberId = orderDao.findMemberIdById(id);
        memberDao.updateName(name, memberId);
        for (Integer setmealId : setmealIds) {
            Order order = new Order();
            order.setId(id);
            order.setMemberId(memberId);
            order.setSetmealId(setmealId);
            order.setOrderDate(date);
            order.setOrderStatus(orderStatus);
            order.setOrderType(orderType);
            orderDao.update(order);
        }
    }
//改变预约状态
    @Override
    public void changeOrderStatus(Integer id) {
        Order order = orderDao.findByOid(id);
        String orderStatus = order.getOrderStatus();
        if ("未到诊".equals(orderStatus)) {
            orderDao.setOrderStatus1(id);
        } else {
            orderDao.setOrderStatus2(id);
        }
    }
 //禁用预约
    @Override
    public void forbidden(Integer id) {
        orderDao.forbidden(id);
    }
    /*查询套餐*/
    @Override
    public List<Setmeal> getOrderAndSetmeal(String telephone) {
        List<Setmeal> list = setmealDao.getOrderAndSetmeal(telephone);
        return list;
    }

    @Override
    public OrderFitness findByIdOrder(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        OrderFitness order = orderDao.findByIdOrder(id);
        order.setSetmeals(setmeal);
        if (order.getId()!=null){
            List<Meals> meals = mealsDao.findById(order.getId());
            order.setMealss(meals);
        }
        if (order.getId()!=null){
            List<Exercise> exercises = exerciseDao.findById(order.getId());
          order.setExercisess(exercises);
        }
        return order;
    }




    //查询预约人数
    @Override
    public List<Integer> findOrderCount(List<String> orderDay) {
        List<Integer> orderCount = new ArrayList<>();
        //遍历
        for (String order : orderDay) {
            //预约人数
            Integer todayNumber = orderDao.getOrderCountByDate(order);
            //添加到集合
            orderCount.add(todayNumber);
        }
        return orderCount;
    }
    //查询到诊人数
    @Override
    public List<Integer> orderGetCount(List<String> orderDay) {
        List<Integer> orderGetCount = new ArrayList<>();
        //遍历
        for (String orderGet : orderDay) {
            //到诊人数
            Integer todayGetNumber = orderDao.getTodayVisitsNumber(orderGet);
            //添加到集合
            orderGetCount.add(todayGetNumber);
        }
        return orderGetCount;
    }
}
